package cn.com.nes.site.rocketmq.config;

import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.common.message.Message;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Component
public class RocketMQProducerConfig {

    @Value("${rocketmq.nameServer}")
    private String nameServer;

    @Value("${rocketmq.producer.group}")
    private String producerGroup;

    private DefaultMQProducer producer;

    @PostConstruct
    public void init() {
        this.producer = new DefaultMQProducer(producerGroup);
        producer.setNamesrvAddr(nameServer);
        try {
            producer.start();
            System.out.println("RocketMQ Producer Started...");
        } catch (Exception e) {
            System.err.println("Error starting RocketMQ Producer: " + e.getMessage());
        }
    }

    // 发送消息
    public void sendMessage(String topic, String messageBody) {
        try {
            Message message = new Message(topic, messageBody.getBytes());
            producer.send(message);
            System.out.println("Message Sent to " + topic + ": " + messageBody);
        } catch (Exception e) {
            System.err.println("Error sending message to " + topic + ": " + e.getMessage());
        }
    }

    // 关闭生产者
    public void shutdown() {
        producer.shutdown();
    }
}
